let refMessageObj = function () {
  let obj = getApp().globalData!.$refDialogObj
  if (obj !== undefined) {
    return obj
  }
  getApp().globalData!.$refDialogObj = {}
  return getApp().globalData!.$refDialogObj
}

const refRouteKey = function () {
  let routes = getCurrentPages() // 获取当前打开过的页面路由数组
  //H5 页面刷新后，返回上一页，会返回空数组
  if (routes.length === 0) {
    return ''
  }
  let rKey = route_uidKey(routes[routes.length - 1])
  return rKey
}

let route_uidKey = function (page: any) {
  let uid = 0
  // #ifdef VUE2
  //vue2 页面的id
  uid = page.$vm._uid
  // #endif
  // #ifndef VUE2
  //vue3 页面的id
  uid = page.__wxExparserNodeId__
  // #endif
  return page.route + '/' + uid
}

let getRef = function (refId: string) {
  let refKey = refRouteKey()
  let refObj = refMessageObj()
  let currentObj = refObj[refKey]
  if (currentObj !== undefined) {
    let ref = currentObj[refId]
    if (ref !== undefined) {
      return ref
    }
  }
  return currentObj
}

let addRefObj = function (refId: string, ref: any) {
  let refKey = refRouteKey()
  let refObj = refMessageObj()
  let currentObj = refObj[refKey]
  if (currentObj !== undefined) {
    currentObj[refId] = ref
  } else {
    let obj: any = {}
    obj[refId] = ref
    refObj[refKey] = obj
  }
}

let removeRefObj = function () {
  let refKey = refRouteKey()
  let refObj = refMessageObj()
  let currentObj = refObj[refKey]
  if (currentObj !== undefined) {
    delete refObj[refKey]
  }
}

export {
  refMessageObj,
  refRouteKey,
  route_uidKey,
  getRef,
  addRefObj,
  removeRefObj
}
